<?php
namespace Futures\Controller;
use Think\Controller;
use Think\FuturesPage;
class OrderController extends BaseController{
	/**
	* 添加支付订单
	* @return
	*/
	public function order_insert(){
		$user_auth= cookie('user_auth');
		$openid=$user_auth['openid'];
		$data['user_id']=$user_auth['uid'];
		//获取余额
		$user_money = M('Follow')->where(array('openid'=>$user_auth['openid']))->getField('money');
		

        $open_price = I('post.lastprice');
        if(!$open_price || $open_price<10){
            $arr['status']=false;
            $arr['msg']="系统繁忙";
            $this->ajaxReturn($arr,'JSON');
        }

		//下单时间控制15:30 到8:30
		//判断是否在购买时间内
		$time=time();
		//$time=1456216200;
		$date=date('Ymd',$time);
        $is_work=is_rest($date);//是否是在工作日；
       	foreach($is_work as $key=>$val){
			$is_work=intval($val);
		}
        
		if($is_work!=0){
			$arr['status']=false;
        	$arr['msg']="节假日休市";
           	$this->ajaxReturn($arr,'JSON');
		}
        //下单时段为交易日：9:00:00-11:30 13:30-15:00 21:00-次日凌晨1:00
        $period_one_start = mktime(9,00,00,date('m',$time),date('d',$time),date('Y',$time));
        $period_one_end = mktime(11,30,00,date('m',$time),date('d',$time),date('Y',$time));

        $period_two_start = mktime(13,30,00,date('m',$time),date('d',$time),date('Y',$time));
        $period_two_end = mktime(15,00,00,date('m',$time),date('d',$time),date('Y',$time));

        $period_three_start= mktime(21,00,00,date('m',$time),date('d',$time),date('Y',$time));
        //$period_three_time= mktime(1,00,00,date('m',strtotime('+1 day')),date('d',strtotime('+1 day')),date('Y',strtotime('+1 day')));
		$period_three_end= mktime(23,59,59,date('m',$time),date('d',$time),date('Y',$time));
        //是工作日并且要在这三个时间段，不是工作日，时间在1点之前，并且前一天是工作日
        $last_date = date('Ymd',strtotime('-1 day'));//前一天
        $is_last_work=is_rest($last_date);//是否是在工作日；
        $is_last_work=$is_last_work[$last_date];
        $cur_night_end=mktime(1,00,00,date('m'),date('d'),date('Y'));
        $cur_night_start=mktime(0,00,00,date('m'),date('d'),date('Y'));
        $is_period_one = (($period_one_start<time())&&(time()<$period_one_end))?true:false;
        $is_period_two = (($period_two_start<time())&&(time()<$period_two_end))?true:false;
        $is_period_three = (($period_three_start<time())&&(time()<$period_three_end))?true:false;

        if(!(($is_last_work==0&&time()<$cur_night_end&&time()>$cur_night_start)||($is_work==0 && ($is_period_one||$is_period_two||$is_period_three)))){
            $arr['status']=false;
            $arr['msg']="下单时段为交易日:9:00-11:30 13:30-15:00 21:00-次日凌晨01:00";
            $this->ajaxReturn($arr,'JSON');
        }

        $start_time= mktime(9,00,00,date('m',$time),date('d',$time),date('Y',$time));
		$end_time= mktime(15,00,00,date('m',$time),date('d',$time),date('Y',$time));
        /*
		if(($time>$end_time || $time<$start_time)){//是工作日，加时间判断
		}else{
			$arr['status']=false;
        	$arr['msg']="购买时间在15:30之后 或 8:30之前";
           	$this->ajaxReturn($arr,'JSON');
		}*/
		//获取开始时间和结束时间
		// if($time<$start_time){
		// 	$time_end_result=strtotime(get_time($time,0));	
		// }elseif($time>$end_time){
		// 	$time_end_result=strtotime(get_time($time,1));
		// }else{
		// 	$time_end_result=strtotime(get_time($time,1));
		// }
        if($is_period_three){
            //21-24结束时间是第二个交易日上午11点半
            $time_end_result=strtotime(get_time($time,1));
             $end_time_value= mktime(11,30,00,date('m',$time_end_result),date('d',$time_end_result),date('Y',$time_end_result));
        }elseif(time()<$cur_night_end&&time()>$cur_night_start){
            //结束时间是交易日上午11点半
            $time_end_result=strtotime(get_time($time,0));
            $end_time_value= mktime(11,30,00,date('m',$time_end_result),date('d',$time_end_result),date('Y',$time_end_result));
        }elseif($is_period_one){    //9-11:30
            $end_time_value= mktime(15,00,00,date('m'),date('d'),date('Y'));        
        }elseif($is_period_two){    //13:00-15:00
            $end_time_value= mktime(1,00,00,date('m',strtotime('+1 day')),date('d',strtotime('+1 day')),date('Y',strtotime('+1 day')));
        }
		
        $start_time_value = $time;
		

		//$end_time_value= mktime(15,00,00,date('m',$time_end_result),date('d',$time_end_result),date('Y',$time_end_result));
		//$start_time_value=mktime(9,00,00,date('m',$time_end_result),date('d',$time_end_result),date('Y',$time_end_result));
		//end
        $futures_id=I('post.futures_id');
        $future = M('futures')->field('price,total')->where(array('id'=>$futures_id))->find();
        if(!$future){
            $arr['status']=false;
            $arr['msg']="请选择正确的合约";;
            $this->ajaxReturn($arr,'JSON');
        }
        $money=I('total_price',0,'doubleval');
        $number=I('post.number');
        $number = intval($number);
        if(!is_int($number) || $number<=0 || $number>1000){
            $arr['status']=false;
            $arr['msg']="合约张数范围为1-1000张";;
            $this->ajaxReturn($arr,'JSON');
        }
        //判断代金卷
        $vouchers = I('post.vouchers');
        $v_money = 0;
        if(!empty($vouchers)){
            foreach($vouchers as $k=>$voucher){
                $voucher_id = $voucher[0];
                $vouchers_num = $voucher[1];
                //查询所有可用代金卷
                $voucher_where['user_id'] = $user_auth['uid'];
                $voucher_where['voucher_id'] = $voucher_id;
                $voucher_where['count'] = array('gt',0);   //未使用
                $voucher_where['overdue_time'] = array('gt',time());
                $v = M('FuturesVoucherRecords')->where($voucher_where)->find();// 查询满足要求的总记录数
                if($vouchers_num>$v['count']){
                    $arr['status']=false;
                    $arr['msg']="代金卷不足！";;
                    $this->ajaxReturn($arr,'JSON');
                }
                $v_money=$v_money+($v['money']*$vouchers_num);
            }
            
        }
        $t_m = doubleval($v_money+$money);  //总价
        $o_m = doubleval($number*$future['price']/10); //原总价
        if($t_m<$o_m){
            $arr['status']=false;
            $arr['msg']="代金券无效使用";;
            $this->ajaxReturn($arr,'JSON');
        }
        $data['voucher_money']=$v_money;

		//判断是否还有余额剩余多少张
		
		$total = $future['total'];
        $where_start['begin_time']=array('eq',$start_time_value);
		$where_start['futures_id']=array('eq',$futures_id);
		$overplus_number_sum=M('futures_order')->field('sum(number) as number')->where($where_start)->find();
		$overplus_number=$overplus_number_sum['number'];
		
        $overplus_status=intval($total)-intval($overplus_number);
        $overplus_status_two=intval($number)-intval($overplus_status);
		if($overplus_status==0){
			$arr['status']=false;
			$arr['msg']="已买完！";;
           	$this->ajaxReturn($arr,'JSON');    	
		}else if($overplus_status_two>0){
			$arr['status']=false;
			$arr['msg']="剩余".$overplus_status."张,不足购买".$number."张";
           	$this->ajaxReturn($arr,'JSON');    	
		}
		
	
		if($user_money<$money){
            $arr['status']=false;
            $arr['msg']="余额不足";
            $this->ajaxReturn($arr,'JSON');
        }
		$rand=$this->GetfourStr(4);//随机4为数
        $data['total_price']=$v_money+$money;
        $data['pay_money']=$money;
		$data['transaction_id']=date('YmdHis').$rand;
		$data['direction']=$direction=I('post.direction');
        $data['open_price'] = I('post.lastprice');
		$data['futures_id']=$futures_id;
		$data['unit_price']=I('post.unit_price');
		$data['number']=$number;
		$data['begin_time']=$start_time_value;
		$data['end_time']=$end_time_value;
		$data['create_time']=time();
		$data['status']=1;
        //dump($_POST);
        $inser_id = M('futures_order')->add($data);
		if(!$inser_id){//添加支付数据
			$arr['status']=false;
        	$arr['msg']="添加支付数据失败";
           	$this->ajaxReturn($arr,'JSON');
		}
        if(!empty($vouchers)){
            foreach($vouchers as $k=>$voucher){
                $voucher_id = $voucher[0];
                $vouchers_num = $voucher[1];
                //查询所有可用代金卷
                modify_voucher($user_auth['uid'],$voucher_id,$vouchers_num,2,'使用代金卷');
                //$v = M('FuturesVoucherRecords')->where($voucher_where)->setDec('count',$vouchers_num); 
            }
        }
		modify_account($openid,-$money,3,'建仓支付');

        //下单支付（type=3）有分销提成
        $route = M('Follow')->where(array('openid'=>$user_auth['openid']))->getField('route');
        if(!empty($route)){
            $routes = explode(',',$route);
            krsort($routes);
            $routes = array_values($routes);
            $commission = M('Config')->where(array('name'=>'COMMISSION_VAL'))->getField('value');
            $commissions = explode(',',$commission);
            foreach($commissions as $k=>$v){
                $is_agent = M('Follow')->where(array('id'=>$routes[$k]))->getField('is_agent');
                if(!$is_agent) countinue;
                $comm = array();
                $comm['order_user_id'] = $user_auth['uid']; //下单者
                $comm['commission_user_id'] = $routes[$k]; //提成者
                $comm['order_id'] = $inser_id;  //订单id
                $comm['status'] = 0;    //未分配
                $comm['create_time'] = time();
                if(strpos($v,'%')>0){
                     $v = $v/100;
                }
               
                $comm['commission'] = abs($money)*$v;   //佣金
                $comm['note'] = "订单：{$data['transaction_id']}佣金提成".(abs($money)*$v).'元';
                //写入佣金表
                $res = M('FuturesCommission')->add($comm);
                if(!$res){
                    //写入日志
                    $nickname = M('Follow')->where(array('id'=>$routes[$k]))->getField('nickname');
                    $file='./Data/commission.txt';
                    $content = date('Ymd His').':'.$nickname.'写入佣金【订单('.$data['transaction_id'].')】失败;\r\n';
                    file_put_contents($file,$content, FILE_APPEND);
                }
            }
        }
        

		$arr['status']=true;
        $arr['msg']="支付成功";
        $this->ajaxReturn($arr,'JSON');	
	}
	public function order_list(){
		$user_auth= cookie('user_auth');
        $user_id=$user_auth['uid'];
        $where['user_id']=array('eq',$user_id);
        $where['status']=array('in','0,1');
        $count=M('futures_order')->where($where)->count();
        $per_num    = 10;//每页条数    自定义
        $Page       = new FuturesPage($count,$per_num);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        //$Page->lastSuffix = false;//最后一页不显示为总页数
        $Page->setConfig(array());
        $show       = $Page->show();// 分页显示输出
        $pages      = ceil($count/$per_num);//总页数
        $this->assign('page',$show);
       	
       	$list = M('futures_order')->where($where)->order('status desc,id desc,begin_time desc')->limit($Page->firstRow.','.$Page->listRows)->select();
     	foreach($list as $k=>$v){
			$list[$k]['create_time']=date("Ymd",$v['begin_time']);//购买时间
			if($v['direction']==1){//购买量和方向
				$list[$k]['number_direction']=($v['number']).'涨';
			}elseif($v['direction']==0){
				$list[$k]['number_direction']=($v['number']).'跌';
			}elseif($v['direction']==2){
                $list[$k]['number_direction']=($v['number']).'平';
            }
			//获取商品名称
			$where_futures['id']=$v['futures_id'];
			$futures_list=M('futures')->field('type_sign,name,code,authority_status,premium')->where($where_futures)->find();	
			$list[$k]['name']=$futures_list['name'];
			$list[$k]['authority_status']=$futures_list['authority_status'];//判断是否有平仓权限
			if($list[$k]['status']==1){
				$future_data = get_futures_data($futures_list['code'],$futures_list['type_sign']); 
            	if(false!==$future_data){//当前价
                	if($futures_list['type_sign']=='commodity'){
                   		$closePrice=$list[$k]['last_price'] = $future_data[8];
                	}elseif($futures_list['type_sign']=='stock'){
                    	$closePrice=$list[$k]['last_price'] = $future_data[3];
                	}
                    if($v['direction']==1){
                        //计算收益公式：盈利=（最新价-开盘价）*手数*权利金 (买涨)
                        $profit = ($closePrice-$v['open_price']);
                    }elseif($v['direction']==0){
                        //计算收益公式：盈利=（最新价-开盘价）*手数*权利金 (买跌)
                        $profit = ($v['open_price']-$closePrice);
                    }elseif($v['direction']==2){
                        //看平分为涨和跌两个方向
                        $ping_d =  $v['open_price']-$closePrice;
                        //如果卖出价大于买入价为涨，计算方式为:买入价*1.01-卖出价
                        ////如果卖出价和买入价相同，计算方式为:买入价*0.01
                        if($ping_d<=0){ //小于0为涨
                            $profit=$closePrice-$v['open_price'];
                        }else{ //大于0为跌
                            //如果卖出价小于买入价为跌，计算方式为:卖出价-买入价0.99
                            $profit=$v['open_price']-$closePrice;
                        }
                        $profit=$futures_list['premium']*2-$profit;
                        if($profit>0){  //在看平范围以内
                            if($ping_d<=0){
                                $closePrice=$o['open_price']+$future['premium']*2;
                            }else{
                                $closePrice=$o['open_price']-$future['premium']*2;
                            }
                        }
                    }
                    //最大值为权益金的三倍，看平的最大值是权益金的两倍TODO
                    if($v['direction']==1){
                        $max_profit = $futures_list['premium']*3;
                        if($profit>$max_profit){
                            $profit = $max_profit;
                            $closePrice=$v['open_price']+$futures_list['premium']*3;
                        }
                    }elseif($v['direction']==0){
                        $max_profit = $futures_list['premium']*3;
                        if($profit>$max_profit){
                            $profit = $max_profit;
                            $closePrice=$v['open_price']-$futures_list['premium']*3;
                        }
                    }
                    
                    $profit = $profit*($v['number']);
                    if($profit<0) $profit=0.00;
                    $list[$k]['profit']=$profit;
            	}
            	
            }else if($list[$k]['status']==0){
				 $list[$k]['last_price'] =0;
				 $profit=0;//盈利
			}
		}
		$url = U('Order/order_list','','');
        $this->assign('url',$url);
		$this->assign('list',$list);
		$this->display();
	}
	public function order_unwind(){
		$orderid=I('post.id');
		$price=I('post.price');
        //获取订单信息
        $o = M('FuturesOrder')->where(array('id'=>$orderid,'status'=>1))->find();
         //判断时间是否是在当日进行交易
        if(date('Ymd',$o['begin_time'])==date('Ymd')){
            //判断是否达到交易结束时间
            //if(date('Ymd',$o['end_time']>time()) continue;
            //获取合约数据
            $future = M('Futures')->field('code,type_sign,stop_loss')->find($o['futures_id']);
            //获取实时数据写入收盘后最新价
            if($price){
				$closePrice=$price;
                if($o['direction']==1){
                    //计算收益公式：盈利=（最新价-开盘价）*手数*权利金 (买涨)
                    //$profit = ($closePrice-$o['open_price'])*$o['number']*$o['premium'];
                    $profit = ($closePrice-$o['open_price']);
                }elseif($o['direction']==0){
                    //计算收益公式：盈利=（最新价-开盘价）*手数*权利金 (买跌)
                    //$profit = ($o['open_price']-$closePrice)*$o['number']*$o['premium'];
                    $profit = ($o['open_price']-$closePrice);
                }
                //盈利最大值
                $stop_loss = $future['stop_loss'];
                if(strpos($stop_loss,'%')>0){
                    $stop_loss = $stop_loss/100;
                }
                $max_profit = $o['open_price']*$stop_loss;
                if($profit>$max_profit){
                    $profit = $max_profit;
                }
                $profit = $profit*($o['number']);
                if($profit<0) $profit=0.00;
                //更改状态和开盘价格
                $data['status'] = 2;
                $data['close_price'] = $closePrice;
                $data['close_time'] = time();
                $data['profit'] = $profit;
                $res = M('FuturesOrder')->where(array('id'=>$o['id']))->save($data);
                if(false===$res){
                    //写入日志
                    $file='./Data/updateorder.txt';
                    $content = date('Ymd His').':批量平仓(订单'.$o['id'].')失败';
                    file_put_contents($file,$content, FILE_APPEND);
                    $arr['status']=false;
					$arr['msg']="平仓失败";
					$this->ajaxReturn($arr,'JSON');
                }else{
                    $openid = M('Follow')->where(array('id'=>$o['user_id']))->getField('openid');
                    if($profit>0){
                        //获取openid
                        modify_account($openid,$profit,5,'订单（'.$o['id'].'）盈利');
                    }
                    //发送通知
                    $title = "您好，您有一笔交易订单已平仓";
                    $content = " ";
                    $content = "订单号：{$o['transaction_id']}\n";
                    $close_time = date('Y-m-d H:i:s',$data['close_time']);
                    $content .= "平仓时间：{$close_time}\n";
                    $content .= "平仓价位：{$data['close_price']}\n";
                    $content .= "盈利资金：{$profit}\n";
                    $w_url=U('Transaction/index');
                    $picurl = $redirect_uri="http://" . $_SERVER['HTTP_HOST'] ."/Public/s4.jpg";
                    send_wx_notify($openid,$title,$content,$w_url,$picurl);                  
					$arr['status']=true;
					$arr['msg']="平仓成功";
					$this->ajaxReturn($arr,'JSON');
                }
           }              
        }else{
			$arr['status']=false;
			$arr['msg']="日期不对还无法平仓";
			$this->ajaxReturn($arr,'JSON'); 
		}
    }
	public function GetfourStr($len){ 
  		$chars_array = array("0","1","2","3","4","5","6","7","8","9"); 
  		$charsLen = count($chars_array) - 1; 
  		$outputstr = ""; 
  		for($i=0;$i<$len;$i++){ 
    		$outputstr .= $chars_array[mt_rand(0, $charsLen)]; 
  		} 
  		return $outputstr; 
	} 
}
?>
